package com.quick.aspect;

import com.quick.config.QuickLoginProperties;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class HeaderAspect {
	private static final Logger logger = LoggerFactory.getLogger(HeaderAspect.class);
	@Autowired
	private QuickLoginProperties quickLoginProperties;
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void header() {}

	@Around("header()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {

			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = requestAttributes.getRequest();
			String url = request.getRequestURI();
			if(quickLoginProperties.getPrintLog()){
				logger.info("【打印抬头】:{}",url);
				Enumeration<String> headerNames = request.getHeaderNames();
				while(headerNames.hasMoreElements()){
					String name = headerNames.nextElement();
					String value = request.getHeader(name);
					logger.info("=>{}",name+":"+value);
				}
			}
			if(quickLoginProperties.getPrintLog()){
				logger.info("【打印Cookie】:{}",url);
				Cookie[] cookies = request.getCookies();
				if(cookies != null && cookies.length > 0){
					for (Cookie cookie : cookies){
						logger.debug("=>{}", cookie.getName()+":"+cookie.getValue());
				}
				}
			}
		return pjp.proceed();

	}
}
